package com.tsit.study.netty.server.server;

import com.tsit.study.netty.server.handler.NettyServerHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author wangxuzhi
 * @date 2020/11/30 13:50
 */
@Component
public class NettyServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private NettyServerHandler nettyServerHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline()
                // 心跳检测机制
                .addLast(new IdleStateHandler(10, 10, 0, TimeUnit.SECONDS))
                // 用于解码request
                .addLast(new HttpRequestDecoder())
                // 用于编码response
                .addLast(new HttpResponseEncoder())
                // 消息处理
                .addLast(nettyServerHandler);
    }
}
